package sg.ImageShack.models
{
	import com.adobe.net.URI;
	
	import flash.display.NativeMenu;
	import flash.display.NativeMenuItem;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.net.FileFilter;
	import flash.net.SharedObject;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.core.Application;
	import mx.core.Window;
	
	import org.httpclient.HttpClient;
	import org.httpclient.http.multipart.FilePart;
	import org.httpclient.http.multipart.Multipart;
	import org.httpclient.http.multipart.Part;
	
	import sg.ImageShack.OptionsDTO;
	import sg.ImageShack.components.AboutWindow;
	import sg.ImageShack.components.AlertNotificationWindow;
	import sg.ImageShack.components.OptionsWindow;
	import sg.ImageShack.components.UploadedHistory;
	
	[Bindable]
	public class AppContext
	{
		public static const MODEL_NAME:String = "ctx";
		private static var _ctx : AppContext;
		
		public var imginfoQName : QName = new QName(new Namespace("http://ns.imageshack.us/imginfo/6/"),"imginfo");
		public var linksQName : QName = new QName(new Namespace("http://ns.imageshack.us/imginfo/6/"),"links"); 
		public var imageLinkQName : QName = new QName(new Namespace("http://ns.imageshack.us/imginfo/6/"),"image_link");
		public var thumbLinkQName : QName = new QName(new Namespace("http://ns.imageshack.us/imginfo/6/"),"thumb_link");
		public var resolutionQName : QName = new QName(new Namespace("http://ns.imageshack.us/imginfo/6/"),"resolution");
		public var widthQName : QName = new QName(new Namespace("http://ns.imageshack.us/imginfo/6/"),"width");
		public var heightQName : QName = new QName(new Namespace("http://ns.imageshack.us/imginfo/6/"),"height");
		public var imagesFilter:FileFilter = new FileFilter("Images (allowed: jpg jpeg png gif bmp tif tiff)", "*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.tif;*.tiff");
		public var httpClient : HttpClient;
		public var uri : URI;
		public var multipart : Multipart;
		public var menu : NativeMenu;
		public var windowsCollection : ArrayCollection = new ArrayCollection;
		public var uploadingMessage : String = "Please wait. Uploading file(s)..."; 
		
		public var currentFileToUpload : File;
		public var isUploading : Boolean = false;
		public var isMenuDisplaying : Boolean = false;
		public var uploadedImages : ArrayCollection = new ArrayCollection;
		public var soHistory : SharedObject;
		public var soOptions : SharedObject;
		public var imageDataCached : Dictionary = new Dictionary;
		public var isConnected : Boolean = true;
		
		public function AppContext()
		{
			initVariables();
		}
		private function initVariables():void
		{
			httpClient = new HttpClient;
			uri = new URI("http://imageshack.us/upload_api.php");
			createMenus();
		}
		public function addFilePart(file : File):Multipart
		{
			var contentType : String = getContentType(file.type);
			var options : OptionsDTO = readOptions();
			multipart = new Multipart([
				new FilePart(file, contentType), //"image/jpeg" 
				new Part("key","3478CIOV6b19cab63a0d22118aca96aa8e2b6a71"),
				new Part("xml","newformat"),
				new Part("rembar",(options.removeBar)?"1":"0"),
				//new Part("optimage","1"),
				//new Part("optsize","resample"),
				new Part("tags",options.tags)
			]);
			
			return multipart;
		}
		public function checkNotClosedWindows():void
		{
			if (windowsCollection.length > 0)
			{
				for each (var win : Window in windowsCollection)
				{
					win.close();
				}
				windowsCollection.removeAll();
			}
		}
		private function createMenus():void
		{
			menu = new NativeMenu;
			var menuItem1:NativeMenuItem = new NativeMenuItem("Open history");
			menuItem1.addEventListener(Event.SELECT, onOpenHistory);
			var menuItem2:NativeMenuItem = new NativeMenuItem("Options");
			menuItem2.addEventListener(Event.SELECT, onOpenOptions);
			var menuItem3:NativeMenuItem = new NativeMenuItem("About");
			menuItem3.addEventListener(Event.SELECT, onOpenAbout);
			var menuItem4:NativeMenuItem = new NativeMenuItem("Check for updates");
			menuItem4.addEventListener(Event.SELECT, onCheckUpdates);
			menu.addItem(menuItem1);
			menu.addItem(menuItem2);
			menu.addItem(menuItem4);
			menu.addItem(menuItem3);
			
			function onCheckUpdates():void
			{
				(Application.application as ImageShack).appUpdate.checkNow();
			}
			function onOpenHistory():void
			{
				UploadedHistory.showHistory();
			}
			function onOpenOptions():void
			{
				OptionsWindow.showOptions();
			}
			function onOpenAbout():void
			{
				AboutWindow.showAbout();
			}
		}
		public function saveOptions(opt : OptionsDTO):void
		{
			soOptions = SharedObject.getLocal("ImageShackOptions");
			if ("options" in soOptions.data)
			{
				for (var prop : String in soOptions.data.options)
				{
					soOptions.data.options[prop] = opt[prop];
				}
				soOptions.flush();
			} else {
				AlertNotificationWindow.showAlert("Error appear while trying to save options. Please try again.");
			}
			
		}
		public function readOptions():OptionsDTO
		{
			soOptions = SharedObject.getLocal("ImageShackOptions");
			var opt : OptionsDTO = new OptionsDTO;
			if ("options" in soOptions.data)
			{
				for (var prop : String in soOptions.data.options)
				{
					opt[prop] = soOptions.data.options[prop];
				}
				return opt;
			} else {
				//save and return default values
				soOptions.data.options = opt;
				soOptions.flush();
				return opt;
			}
		}
		public function saveHistory(result : ArrayCollection):void
		{
			soHistory = SharedObject.getLocal("ImageShackHistory");
			if (!("uploadedImages" in soHistory.data))
			{
				soHistory.data.uploadedImages = result;
			} else {
				
				for each (var img : * in result)
				{
					(soHistory.data.uploadedImages as ArrayCollection).addItemAt(img, 0);
				}
			}
			soHistory.flush();
		}
		public function readHistory():ArrayCollection
		{
			soHistory = SharedObject.getLocal("ImageShackHistory");
			if ("uploadedImages" in soHistory.data)
			{
				return soHistory.data.uploadedImages;
			} else {
				return null;
			}
		}
		public function clearHistory():void
		{
			soHistory = SharedObject.getLocal("ImageShackHistory");
			soHistory.clear();
			soHistory.flush();
		}
		public function getContentType(fileType : String):String
		{
			switch (fileType.toUpperCase())
			{
				case ".JPG": return "image/jpeg";
			   case ".JPEG": return "image/jpeg";
			    case ".PNG": return "image/png";
			    case ".GIF": return "image/gif";
			    case ".BMP": return "image/bmp";
			    case ".TIF": return "image/tiff";
			   case ".TIFF": return "image/tiff";
			   	    default: null;
			}
			return null;
		} 
		public static function get ctx():AppContext
		{
			if (!_ctx)
			{
				_ctx = new AppContext;
			}
			return _ctx;
		}
		
		public var resizeProvider : ArrayCollection = 
						new ArrayCollection([{data:'', label:"original size"},
											 {data:'100x100', label:"100x75 (avatar)"},
											 {data:'150x150', label:"150x112 (thumbnail)"},
											 {data:'320x320', label:"320x240 (for websites and email)"},
											 {data:'640x640', label:"640x480 (for message boards)"},
											 {data:'800x800', label:"800x600 (15-inch monitor)"},
											 {data:'1024x1024', label:"1024x768 (17-inch monitor)"},
											 {data:'1280x1280', label:"1280x1024 (19-inch monitor)"},
											 {data:'1600x1600', label:"1600x1200 (21-inch monitor)"}]);
		
		public var retriesProvider : ArrayCollection = 
						new ArrayCollection([{data:0, label:"Do not retry"},
											 {data:1, label:"Retry once"},
											 {data:2, label:"Retry twice"},
											 {data:3, label:"Always retry"}]);
	}
}